<template>
  <div class="form-connector">
    <template v-if="selectType == 1">
      <!-- 选项模式 -->
      <div class="select-wrap">
        <el-select :disabled="disabled" :value="connectorValue" style="width: 100%" value-key="bizId" filterable :multiple="isMulti" :remote="tableData.length > 0" reserve-keyword popper-append-to-body popper-class="select-connector-item" :loading-text="$t('common.base.loadMore')" :no-match-text="$t('common.base.tip.noData')" :no-data-text="$t('common.base.tip.noData2')" @change="updateConnector" :placeholder="$t('common.placeholder.select')" :remote-method="search" @focus="handleSelectFocus" v-el-select-loadmore="loadMoreOptions">
          <el-option v-for="option in tableData" :key="option.bizId" :label="connectorNames(option)" :value="option">
            <div v-for="column in columns" :key="column.enName">
              <FormSelectConnector :field="column" :value="option"></FormSelectConnector>
            </div>
          </el-option>
        </el-select>
        <el-button v-if="showCreateButton" class="create-button" type="text" icon="el-icon-circle-plus-outline" @click="createForm">{{$t('common.base.create')}}</el-button>
      </div>
    </template>
    <template v-else-if="selectType == 2">
      <!-- 列表模式 -->
      <div v-if="selectColumns && selectColumns.length" class="form-relation-form">
        <el-button v-if="!disabled" class="add-subform-btn" icon="el-icon-plus" @click="handleAdd">
          {{ $t('common.base.add2') }}
        </el-button>
        <el-button v-if="showCreateButton && !disabled" @click="createForm">
          {{ $t('common.base.create') }}
        </el-button>
        <div class="table-box">
          <ConnectorModuleConnectorComponentTable
            ref="multipleTable"
            :fields="relationColumns"
            :values="relationFormData"
            :showDeleteButton="!disabled"
            :isMulti="Boolean(isMulti)"
            :showIndex="true"
            :form-table-columns="subFormFieldList"
            @delete="handleDelete"
          />
        </div>
        <base-modal :show.sync="visible" :title="title" width="1000px" @closed="handleClickCancel">
          <div class="content" v-loading="loading">
            <div class="search-box" v-if="supportKeywordSearch">
              <form @submit.prevent="handleSearch()">
                <div class="customer-list-base-search-group input-with-append-search">
                  <el-input v-model="keyword" :placeholder="$t('common.placeholder.inputKeyWordToSearch')" v-trim:blur class="mar-r-12">
                    <i slot="prefix" class="el-input__icon el-icon-search"></i>
                    <el-button type="primary" slot="append" @click="handleSearch" native-type="submit">{{ $t('common.base.search') }}</el-button>
                  </el-input>
                  <el-button
                    type="plain-third"
                    @click="
                      () => {
                        keyword = '';
                        handleSearch();
                      }
                    "
                    >{{ $t('common.base.reset') }}</el-button
                  >
                </div>
              </form>
            </div>
            <div class="table-box">
              <ConnectorModuleConnectorComponentTable :fields="columns" :values="tableData" :isMulti="Boolean(isMulti)" :showIndex="false" :loading="loading" @selectionChange="handleSelectionChange" />
            </div>
            <div class="pagping-box">
              <template v-if="supportKeywordSearch">
                <el-pagination
                  :background="true"
                  :current-page="pageInfo.pageNum"
                  :page-size="pageInfo.pageSize"
                  :total="total"
                  class="base-pagination"
                  layout="total, prev, pager, next"
                  @current-change="handleCurrentChange"
                >
                </el-pagination>           
              </template>
              <template v-else>
                <div class="connect-third-form__pagination">
                  <connector-module-connector-card-multi-outside-app-pagination 
                    :page-info="{ ...pageInfo, hasNextPage }" 
                    :page-num="pageInfo.pageNum"
                    :show-sizes="false"
                    @changePageNum="handleThirdFormPageChange"
                  />
                  <!-- <el-button type="primary" v-show="pageInfo.pageNum !== 1" @click="handleThirdFormPageChange('prev')">上一页</el-button>
                  <el-button type="primary" v-show="hasNextPage" @click="handleThirdFormPageChange('next')">下一页</el-button> -->
                </div>
              </template>
            </div>
          </div>

          <div slot="footer">
            <el-button @click="handleClickCancel">{{ $t('common.base.cancel') }}</el-button>
            <el-button type="primary" @click="onSubmit">{{ $t('common.base.save') }}</el-button>
          </div>
        </base-modal>
      </div>
    </template>
  </div>
</template>

<script>
/* mixin */
import FormMixin from '@src/component/form/mixin/form';
/* api */
import { getConnectorCardDataListV2, getAuthTemplateList } from "@src/modules/connector/api";
import _ from 'lodash'
import {convertFormValueToServerValue, getSortConnectorToFieldsByShowFieldNameList} from "@src/modules/connector/util";
import { isArray, isElement, isEmpty, isObject, isFalsy} from "@src/util/type";
import * as FormUtil from '@src/component/form/util';
import {
  ConnectorCardMultiFixedFields,
  ConnectorModuleConnectorComponentTable
} from "@src/modules/connector";
import ConnectorModuleConnectorCardMultiOutsideAppPagination from '@src/modules/connector/components/connector-card/multi-outside-pagination'
import { getFiledLaForHttp } from '@src/api/ConnectorApi';
import FormSelectConnector from './FormSelectConnector';

import { ConnectorOptionsFieldOptionValueTypeEnum } from '@src/modules/connector';

import { ConnectorOptionsActionEnum, ConnectorBizTypeEnum } from '@src/modules/connector/model/enum';
import AuthUtil from '@src/util/auth';
import AuthEnum from '@model/enum/AuthEnum.ts';
import { connectorJumpToCreate } from '@src/component/form/components/FormConnector/components/FormConnectorDataRuleSetting/utils/index.ts'

export default {
  name: 'form-connector',
  mixins: [FormMixin],
  inject: ['isEdit'],
  props: {
    value: {
      default: () => [],
    },
  },
  watch: {
    // 编辑工单 || 数据回显
    value(newValue) {
      this.relationFormData = newValue;
    },
    connector: {
      handler(newValue) {
        this.initSelectColumns(newValue);
      },
      immediate: true,
    },
  },
  components: {
    ConnectorModuleConnectorComponentTable,
    FormSelectConnector,
    ConnectorModuleConnectorCardMultiOutsideAppPagination
  },
  data() {
    return {
      relationFormData: this.value,
      tableData: [],
      options: [],
      loadMoreOptions: {
        disabled: false,
        callback: this.loadMore,
        distance: 10,
      },
      hasNextPage: true,
      loading:false,
      visible:false,
      multipleSelection: this.value,
      total:0,
      pageInfo:{
        pageNum: 1,
        pageSize: 10,
      },
      keyword: '',
      fromBizData: {},
      selectColumns: [],
      paasAddAuth: false, // paas新增权限
    };
  },
  computed: {
    supportKeywordSearch() {
      return this.connector?.supportKeywordSearch
    },
    connectorValue() {
      return this.isMulti ? this.relationFormData : this.relationFormData[0];
    },
    // 标题
    title() {
      return this.$t('common.connector.addTitle', { title: this.field?.displayName || '' });
    },
    // 表单表头
    columns() {
      let columns = [];
      if (this.selectColumns?.length > 0) {
        columns = [...this.selectColumns];
        columns.map(field => {
          field.label = field.cnName;
          field.field = field.enName;
          field.formType = field.fieldType;
          field.fieldName = field.enName;
        });
      }
      return columns;
    },
    relationColumns() {
      return (this.columns || []).concat(ConnectorCardMultiFixedFields);
    },
    setting() {
      return this.field?.setting || {};
    },
    connector() {
      return this.setting?.connector;
    },
    // 数据自动带入
    isMatch() {
      return this.setting?.isMatch;
    },
    // 多选
    isMulti() {
      return this.setting?.isMulti;
    },
    // 展示模式
    selectType() {
      // 默认选项模式
      return this.setting?.selectType || 1;
    },
    toFieldList() {
      return this.connector?.actionList?.find(action => action.action === ConnectorOptionsActionEnum.Select)?.toResponseFieldList || [];
    },
    relationFieldMap() {
      // 关联字段对象
      const relationFieldMap = {};

      // 连接器查询条件
      const selectFieldOptionsList = this.connector?.selectFieldOptionsList || [];

      if (isEmpty(selectFieldOptionsList)) {
        return relationFieldMap;
      }

      // 找到连接器查询条件为对应字段的条件
      const relationOptions = selectFieldOptionsList.filter(item => item.valueType == ConnectorOptionsFieldOptionValueTypeEnum.FromField);

      if (isEmpty(relationOptions)) {
        return relationFieldMap;
      }

      relationOptions.forEach(item => {
        // 找到连接器查询条件的对应字段的值
        const { value } = item;

        if (isEmpty(value) || isFalsy(value)) {
          return;
        }

        // 找到对应字段的值
        let relationFieldName = value?.[0] || '';

        if (isEmpty(relationFieldName)) {
          return;
        }

        const isHaveChild = relationFieldName.includes('.');

        if (isHaveChild) {
          relationFieldName = relationFieldName.split('.')[0];
        }
        
        relationFieldMap[relationFieldName] = item
        
      })
      
      return relationFieldMap
      
    },
    /* 自定义字段 */
    subFormFieldList() {
      let { subFormFieldList = [] } = this.field?.setting || {};
      return subFormFieldList.map(field => {
        field.label = field.displayName;
        field.field = field.fieldName;
        return field;
      });
    },
    // 是否显示新建按钮
    showCreateButton() {
      const { toBizType } = this.connector
      const canAddToBizTypeList = [
        {
          toBizType: ConnectorBizTypeEnum.Contract, // 新建合同
          auth: () => AuthUtil.hasAuth(this.globalLoginUserAuth, AuthEnum.CONTRACT_ADD)
        },
        {
          toBizType: ConnectorBizTypeEnum.Paas, // 新建工单
          auth: () => this.paasAddAuth
        },
        // {
        //   toBizType: ConnectorBizTypeEnum.Task, // 新建工单
        //   auth: () => AuthUtil.hasAuth(this.globalLoginUserAuth, AuthEnum.TASK_ADD)
        // },
        // {
        //   toBizType: ConnectorBizTypeEnum.Event, // 新建事件
        //   auth: () => AuthUtil.hasAuth(this.globalLoginUserAuth, AuthEnum.SERVICE_CREATE)
        // },
        // {
        //   toBizType: ConnectorBizTypeEnum.Customer, // 新建客户
        //   auth: () => AuthUtil.hasAuth(this.globalLoginUserAuth, AuthEnum.CUSTOMER_CREATE)
        // },
        // {
        //   toBizType: ConnectorBizTypeEnum.Product, // 新建产品
        //   auth: () => AuthUtil.hasAuth(this.globalLoginUserAuth, AuthEnum.PRODUCT_CREATE)
        // }
      ]

      const canAddToBizTypeItem = canAddToBizTypeList.find(item => item.toBizType === toBizType)
      return !!canAddToBizTypeItem?.auth()
    },
  },
  created() {
    // this.field.subFormFieldList = this.field?.setting?.subFormFieldList || []
    // 切换工单类型将选择的连接器清空
    this.$eventBus.$on('connector-related-field-clear', this.handleClearConnector);
  },
  mounted() {
    this.$nextTick(() => {
      this.getAuthTemplateList();
      const isFirst = !this.isEdit;
      this.genRelationFieldDataValueMap();
      this.getDataList(isFirst);
    });
  },
  methods: {
    handleSelectFocus() {
      this.relationFormData = [];
      this.tableData = [];
      this.pageInfo.pageNum = 1;
      this.genRelationFieldDataValueMap();
      this.search();
    },
    handleThirdFormPageChange(type, pageNum) {
      type === 'next'
        ? this.handleCurrentChange(pageNum + 1)
        : this.handleCurrentChange(pageNum - 1)
    },
    // 连接器列表模式显示字符串
    connectorNames(option) {
      // 取showFieldNameList第一个字段的值
      const fieldName = this.connector?.showFieldNameList?.[0];
      if (fieldName && option) {
        const result = option[fieldName];
        if (isObject(result)) {
          return result.name || result.displayName || result.taskNo || '';
        }
        return result || '';
      }
    },
    // 加载更多
    loadMore() {
      if (!this.hasNextPage) return;
      this.pageInfo.pageNum++;
      this.getDataList();
    },
    updateConnector(newValue) {
      // console.log('updateConnector', newValue)
      // 选项模式
      this.relationFormData = this.isMulti ? newValue : [newValue];
      this.inputForValue(this.relationFormData);
    },
    handleClearConnector() {
      if (this.relationFormData.length) this.relationFormData = [];
    },
    getServerValue(value, field) {
      // console.log('FormConnector getServerValue', value, field)
      if (!value) return '';
      const formType = field?.formType || field?.fieldType || '';
      if (isObject(value)) {
        // 空对象
        if (isEmpty(value)) return '';
        const val = convertFormValueToServerValue(value, field);
        // 人员传数组
        return formType === 'user' ? [val] : val;
      }
      // 如果值是数组 比如客户
      if (isArray(value)) {
        // 空数组
        if (!value.length) return [''];
        const val = value.map(item => {
          if (isObject(item)) {
            item = convertFormValueToServerValue(item, field);
          }
          return item;
        });
        return val;
      }
      // 下拉菜单需要传[]格式
      if (formType === 'select') {
        value = [value];
      }
      return value;
    },
    getRowKeys(row) {
      return row.bizId;
    },
    handleAdd() {
      console.log('FormConnector handleAdd');
      // if (this.relationFormData.length >= SUBFORM_FIELDS_ADD_LENGTH_MAX) return this.$message.warning(`当前支持添加最多${SUBFORM_FIELDS_ADD_LENGTH_MAX}条数据`);
      // 勾选上的数据
      this.$eventBus.$emit('toggleRowSelection', { selections: this.relationFormData });
      this.visible = true;
      // 在组件内计算关联关系 不需要在各自表单的update里面计算
      this.genRelationFieldDataValueMap();
      this.getDataList();
    },
    onSubmit(){
      console.log('FormConnector onSubmit')

      let form = FormUtil.initialize(this.subFormFieldList, {});
      if (this?.field?.setting?.isMulti) {
        let newChecked = this.multipleSelection.map(item => Object.assign({}, item, form));
        this.relationFormData = this.relationFormData.concat(newChecked);
      } else {
        // 取原先已添加的数据（交集）
        let originChecked = (this.relationFormData || []).filter(item => this.multipleSelection.some(s => s.bizId === item.bizId));
        // 取新添加的数据（差集）
        let newChecked = this.multipleSelection.filter(item => originChecked.every(s => s.bizId !== item.bizId));

        // 初始化化新数据
        newChecked = newChecked.map(item => Object.assign({}, item, form));

        this.relationFormData = originChecked.concat(newChecked);
      }
      

      this.inputForValue(this.relationFormData);
      this.visible = false;
    },
    handleSelectionChange(val) {
      console.log('FormConnector handleSelectionChange', val);
      // console.log('handleSelectionChange', val)
      this.multipleSelection = val;
    },
    async handleDelete(row) {
      console.log('FormConnector handleDelete', row);
      const index = this.relationFormData.findIndex(item => item.bizId == row.bizId);
      this.relationFormData.splice(index, 1);
      this.inputForValue(this.relationFormData);
      // 删除的时候也去掉旧的选中的列表数据
      this.multipleSelection = this.multipleSelection.filter(item => item.bizId !== row.bizId);
    },
    search(keyword = '') {
      this.keyword = keyword;
      if (keyword) this.pageInfo.pageNum = 1;
      this.getDataList();
    },
    /* 获取添加时弹窗内的列表数据 */
    getDataList(isFirst) {
      if (this.pageInfo?.pageNum == 1) {
        this.tableData = [];
      }
      console.log('FormConnector getDataList', this.fromBizData);
      const { fromBizType, fromBizTypeId, toBizType, toBizTypeId, additionalId, selectFieldOptionsList } = this.connector;
      // fromBizData 是配置的对应查询条件 只需传配置的对应字段的
      const params = {
        ...this.pageInfo,
        additionalId,
        fromBizType,
        fromBizTypeId,
        fromBizId: '', // 业务id 新建的时候不存在
        toBizType,
        toBizTypeId,
        fromBizData: this.fromBizData,
        useScene: 'FORM_CONTROL',
        keyword: this.keyword,
      };
      // console.log('params', params)
      this.loading = true;
      getConnectorCardDataListV2(params)
        .then(res => {
          const { success, data } = res;
          if (!success || !data) return;
          if (this.selectType == 1) {
            let interfaceDatList = data.list || []
            if(this.relationFormData.length > 0 ) {
              const valueBizIds = this.relationFormData.map(item=> item.bizId)
              const existItems = this.tableData.filter(item=> valueBizIds.includes(item.bizId))
              existItems.length === 0 ?
                interfaceDatList.unshift(...this.relationFormData)
                :
                interfaceDatList = interfaceDatList.filter(item=> !valueBizIds.includes(item.bizId))
            } 
            this.tableData = this.tableData.concat(interfaceDatList || []);
          } else {
            // supportKeywordSearch  代表支持搜索以及分页显示问题 代表第三方表单
            this.tableData = data.list || [];
          }
          if (toBizType == 'PRODUCT') {
            this.tableData = this.tableData.map(item => {
              if (isObject(item.type)) {
                item.type = item.type?.pathName ?? item.type?.catalogName
              }
              return item
            })
          }
          this.hasNextPage = data.hasNextPage;
          this.total = data.total || 0;

          // 如果设置了数据自动带入
          if (isFirst && this.isMatch && this.tableData.length && !this.relationFormData.length) {
            const firstData = this.tableData[0];
            // 多选或者列表模式是数组
            this.relationFormData = [firstData];
            this.multipleSelection = [firstData]
            // 勾选上默认的数据
            // this.$eventBus.$emit('toggleRowSelection', { selections: this.relationFormData })
            this.inputForValue(this.relationFormData);
          }
        })
        .finally(() => {
          this.loading = false;
        })
        .catch(err => {
          console.error('err', err);
        });
    },
    // 关键字搜素
    handleSearch: _.debounce(function () {
      console.log('FormConnector handleSearch');
      this.pageInfo.pageNum = 1;
      this.getDataList();
    }, 500),

    // 切换页数
    handleCurrentChange(val) {
      console.log('FormConnector handleCurrentChange', val);
      this.pageInfo.pageNum = val;
      this.getDataList();
    },
    genRelationFieldDataValueMap() {
      this.fromBizData = {};
      // 在组件内计算关联关系 不需要在各自表单的update里面计算
      const selectFieldOptionsList = this.connector?.selectFieldOptionsList;
      if (selectFieldOptionsList && selectFieldOptionsList.length) {
        const columns = selectFieldOptionsList.filter(item => item.valueType === 2);
        // 判断当前字段是否跟在连接器配置里面的查询字段有关联
        for (const column of columns) {
          if (column.value && isArray(column.value)) {
            for (const field of this.fields) {
              const originCorrespondingFieldName = column.value?.[0] || '';

              if (originCorrespondingFieldName.includes(field.fieldName) && this.formValue[field.fieldName]) {
                // console.log('column', fieldName, formType, newValue)
                const serverValue = this.getServerValue(this.formValue[field.fieldName], field);
                if (serverValue) this.fromBizData[field.fieldName] = serverValue;
              }
            }
          }
        }
      }
    },
    updateConnectorDataByRelationField(field) {
      const fieldName = field?.fieldName || '';
      const isHaveRelationField = this.relationFieldMap[fieldName];

      if (!isHaveRelationField) {
        console.warn('updateConnectorDataByRelationField', '没有关联字段');
        return;
      }
      
      this.$eventBus.$emit('toggleRowSelection', { selections: this.relationFormData })
      this.genRelationFieldDataValueMap()
      this.relationFormData = []
      this.inputForValue(this.relationFormData)
      
      const isFirst = true
      this.getDataList(isFirst)
    },
    async initSelectColumns(newValue) {
      if (newValue) {
        let { showFieldNameList, additionalId } = newValue;
        if (showFieldNameList) {
          let arr = getSortConnectorToFieldsByShowFieldNameList(this.toFieldList, showFieldNameList);
          try {
            // 表单name 国际化
            const { showFieldNameList } = this.connector;
            let res = await getFiledLaForHttp({
              id: additionalId,
              showFieldNameList,
            });
            if (res.status === 0) {
              if (res.data?.length) {
                this.selectColumns = arr.map(i => {
                  let realName = res.data.find(j => j.enName === i.enName)?.cnName || '';
                  return {
                    ...i,
                    cnName: realName,
                    label: realName,
                  };
                });
              } else {
                this.selectColumns = arr;
              }
            }
          } catch (error) {
            console.error(error, 'getFiledLaForHttp is Error');
            this.selectColumns = arr;
          }
        }
      }
    },
    createForm() {
      connectorJumpToCreate(this.connector);
    },
    handleClickCancel() {
      this.visible = false;
      this.keyword = '';
      this.total = 0;
      // 取消或保存初始化触发器表格数据
      this.pageInfo = {
        pageNum: 1,
        pageSize: 10,
      }
    },

    /*获取paas新增权限*/
    async getAuthTemplateList() {
      const { toBizTypeId, toBizType} = this.connector
      if(toBizType !== ConnectorBizTypeEnum.Paas || !toBizTypeId) return

      try {
        const { data = {} } = await getAuthTemplateList({templateBizId: this.connector.toBizTypeId})
        this.paasAddAuth = data?.approveAuth == 1
      } catch (e) {
        console.error(e)
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.form-relation-form {
  .add-subform-btn {
    color: $color-primary;
    border-color: $color-primary-light-2;
    background-color: $color-primary-light-1;
    // margin-bottom: 8px;
    &:hover {
      background: $color-primary-light-6;
      border-color: $color-primary-light-6;
      color: #fff;
    }
  }
}
.content{
  padding:20px;
  min-height: 400px;
  .search-box{
    width: 50%;
    ::v-deep .el-input__inner {
      border: 1px solid #e0e1e2 !important;
    }
    ::v-deep .el-input__inner:focus {
      outline: none;
      border-color: $color-primary-light-6 !important;
    }
  }

  .base-pagination {
    border: none;
  }
}
.table-box{
  margin:8px 0;
  height: calc(100% - 40px);
  ::v-deep .el-table{
    border: 1px solid #ebeef5;
  }
}
.search-box {
  display: flex;
  width: 440px;
  justify-content: space-between;
  .el-input {
    width: 300px;
    input {
      height: 34px;
      line-height: 34px;
      width: 300px;
    }
  }
}
.select-wrap {
  position: relative;
  .create-button {
    position: absolute;
    right: 10px;
    top: 0;
    z-index: 999;
  }
}
</style>
<style lang="scss">
.connector-table-select-single {
  thead {
    .el-table-column--selection .cell {
      display: none !important;
    }
  }
}
.select-connector-item {
  .el-select-dropdown__item {
    * {
      margin: 0;
    }
    // width: 580px;
    height: auto !important;
    padding: 10px 12px;
    // margin-right: -11px;
    border-bottom: 1px solid #f5f7fa;
    h3 {
      font-size: 14px;
      font-weight: 500;
      line-height: 24px;
    }

    .option-item-font {
      display: flex;
      line-height: 24px;
      label {
        width: 110px;
      }
      & > span {
        font-size: 12px;
        color: #666666;
        padding-right: 10px;

        & > label {
          padding: 0;
          width: auto !important;
        }
        & > span {
          @include text-ellipsis();
        }
      }
    }
  }
}

.connect-third-form__pagination{
  display: flex;
  justify-content: flex-end;
}
</style>
